package com.fit.utils.ee;

import com.fit.utils.se.EmptyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * 获取客户端地址
 * 有时候获取不到，不是很稳定(获取很慢,最好异步获取)
 * @author hcl
 * 
 */
public class ClientAddressUtil {

	private static Logger log = LoggerFactory.getLogger(ClientAddressUtil.class);
	
	/**
	 * 获取客户端IP
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (EmptyUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (EmptyUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(EmptyUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
			ip=request.getHeader("X-Real-IP");
		}
		if(EmptyUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if ("127.0.0.1".equals(ip)) {
				//根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
					ip = inet.getHostAddress();
				} catch (UnknownHostException e) {
					log.error("获取本机ip异常", e);
					throw new RuntimeException("获取本机ip异常", e);
				}
			}
		}
		//对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if(EmptyUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip) && ip.length() > 15){//"***.***.***.***".length() = 15
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
            }
		}
		return ip;
	}

	/**
	 * 根据IP获取mac地址,只支持windows
	 * @param ip
	 * @return
	 * @throws IOException 
	 */
//	public static String getMACAddr(String ip) throws IOException  {
//		String macAddress = null;
//		BufferedReader br = null;
//		try {
//			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
//			Reader reader = new InputStreamReader(p.getInputStream());
//			br = new BufferedReader(reader);
//			String str = null;
//			while((str = br.readLine()) != null){
//				if(str.matches("^.*(([^-]{2})-){5}.{2}$")){
//					macAddress = str.substring(str.length() - 17, str.length());
//					break;
//				}
//			}
//		} finally{
//			IOUtil.close(br);
//		}
//		return macAddress;
//	}
	
	/**
	 * 获取mac地址,只支持windows
	 * @param request
	 * @return
	 * @throws IOException 
	 */
//	public static String getMACAddr(HttpServletRequest request) {
//		String ip = ClientAddressUtil.getIpAddr(request);
//		try {
//			return EmptyUtils.isEmpty(ip) ? null : ClientAddressUtil.getMACAddr(ip);
//		} catch (IOException e) {
//			log.error("获取mac地址异常!", e);
//			throw new RuntimeException("获取mac地址异常!", e);
//		}
//	}
	

}
